<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>情侣AI助手 - 让爱情更甜蜜</title>
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- PWA配置 -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="light-content">
    <meta name="apple-mobile-web-app-title" content="情侣助手">
    <meta name="theme-color" content="#EC4899">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'love-pink': '#EC4899',
                        'love-purple': '#8B5CF6',
                        'love-blue': '#3B82F6'
                    }
                }
            }
        }
    </script>
    
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #EC4899 0%, #8B5CF6 50%, #3B82F6 100%);
        }
        .heart-beat {
            animation: heartBeat 1.5s ease-in-out infinite;
        }
        @keyframes heartBeat {
            0% { transform: scale(1); }
            14% { transform: scale(1.1); }
            28% { transform: scale(1); }
            42% { transform: scale(1.1); }
            70% { transform: scale(1); }
        }
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-gray-50 dark:bg-gray-900 min-h-screen">
    <!-- 用户选择界面 -->
    <div id="userSelection" class="min-h-screen flex items-center justify-center p-4">
        <div class="text-center">
            <div class="gradient-bg rounded-full w-24 h-24 mx-auto mb-6 flex items-center justify-center">
                <span class="text-4xl text-white heart-beat">💕</span>
            </div>
            <h1 class="text-3xl font-bold text-gray-800 dark:text-white mb-4">情侣AI助手</h1>
            <p class="text-gray-600 dark:text-gray-300 mb-8">选择你的身份，开始甜蜜之旅</p>
            
            <div class="space-y-4 max-w-sm mx-auto">
                <button onclick="selectUser('boyfriend')" 
                        class="w-full bg-blue-500 hover:bg-blue-600 text-white rounded-lg py-4 px-6 text-lg font-semibold transition-colors">
                    🤵 我是男友
                </button>
                <button onclick="selectUser('girlfriend')" 
                        class="w-full bg-pink-500 hover:bg-pink-600 text-white rounded-lg py-4 px-6 text-lg font-semibold transition-colors">
                    👩 我是女友
                </button>
            </div>
        </div>
    </div>

    <!-- 配置界面 -->
    <div id="configPanel" class="min-h-screen flex items-center justify-center p-4 hidden">
        <div class="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full">
            <h2 class="text-2xl font-bold text-gray-800 dark:text-white mb-6 text-center">初始配置</h2>
            
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        你的名字
                    </label>
                    <input type="text" id="userName" placeholder="输入你的名字" 
                           class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 text-base focus:outline-none focus:ring-2 focus:ring-love-pink bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        对方的名字
                    </label>
                    <input type="text" id="partnerName" placeholder="输入TA的名字" 
                           class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 text-base focus:outline-none focus:ring-2 focus:ring-love-pink bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        在一起的日期
                    </label>
                    <input type="date" id="anniversaryDate" 
                           class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 text-base focus:outline-none focus:ring-2 focus:ring-love-pink bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        对方的生日
                    </label>
                    <input type="date" id="partnerBirthday" 
                           class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 text-base focus:outline-none focus:ring-2 focus:ring-love-pink bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Deepseek API Key (可选)
                    </label>
                    <input type="password" id="apiKey" placeholder="输入API Key获得智能建议" 
                           class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 text-base focus:outline-none focus:ring-2 focus:ring-love-pink bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
                </div>
                
                <button onclick="saveConfig()" 
                        class="w-full gradient-bg text-white rounded-lg py-4 font-semibold transition-colors">
                    💕 开始甜蜜之旅
                </button>
            </div>
        </div>
    </div>

    <!-- 主应用界面 -->
    <div id="mainApp" class="hidden">
        <!-- 头部 -->
        <div class="gradient-bg text-white p-4 shadow-lg">
            <div class="max-w-md mx-auto flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
                        <span id="userIcon" class="text-xl"></span>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg" id="appTitle"></h1>
                        <p class="text-sm opacity-90" id="subtitle"></p>
                    </div>
                </div>
                <button onclick="showSettings()" class="text-white">
                    ⚙️
                </button>
            </div>
        </div>

        <div class="max-w-md mx-auto">
            <!-- 今日提醒卡片 -->
            <div class="m-4 bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
                <h3 class="font-bold text-lg text-gray-800 dark:text-white mb-3 flex items-center">
                    📅 今日提醒
                </h3>
                <div id="dailyReminders" class="space-y-2">
                    <!-- 动态生成提醒内容 -->
                </div>
            </div>

            <!-- AI智能建议 -->
            <div class="m-4 bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
                <h3 class="font-bold text-lg text-gray-800 dark:text-white mb-3 flex items-center">
                    💡 智能建议
                </h3>
                <div id="aiSuggestions">
                    <div class="text-gray-600 dark:text-gray-400 text-center py-4">
                        正在为你生成个性化建议...
                    </div>
                </div>
                <button onclick="getNewSuggestion()" 
                        class="w-full mt-3 bg-love-pink text-white rounded-lg py-2 font-semibold">
                    🔄 换一个建议
                </button>
            </div>

            <!-- 关系状态 -->
            <div class="m-4 bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
                <h3 class="font-bold text-lg text-gray-800 dark:text-white mb-3 flex items-center">
                    💖 恋爱指数
                </h3>
                <div class="space-y-3">
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600 dark:text-gray-400">甜蜜度</span>
                        <div class="flex items-center">
                            <div class="w-32 h-2 bg-gray-200 rounded-full mr-2">
                                <div class="h-2 bg-pink-500 rounded-full" style="width: 85%"></div>
                            </div>
                            <span class="text-sm font-semibold">85%</span>
                        </div>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600 dark:text-gray-400">关怀度</span>
                        <div class="flex items-center">
                            <div class="w-32 h-2 bg-gray-200 rounded-full mr-2">
                                <div class="h-2 bg-blue-500 rounded-full" style="width: 92%"></div>
                            </div>
                            <span class="text-sm font-semibold">92%</span>
                        </div>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600 dark:text-gray-400">互动度</span>
                        <div class="flex items-center">
                            <div class="w-32 h-2 bg-gray-200 rounded-full mr-2">
                                <div class="h-2 bg-purple-500 rounded-full" style="width: 78%"></div>
                            </div>
                            <span class="text-sm font-semibold">78%</span>
                        </div>
                    </div>
                </div>
                <div class="mt-3 text-center">
                    <span class="text-2xl" id="relationshipDays">❤️ 在一起 0 天</span>
                </div>
            </div>

            <!-- 消息中心 -->
            <div class="m-4 bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
                <div class="flex justify-between items-center mb-3">
                    <h3 class="font-bold text-lg text-gray-800 dark:text-white flex items-center">
                        💕 爱的信箱
                    </h3>
                    <div class="flex space-x-2">
                        <span id="messageNotification" class="hidden bg-red-500 text-white text-xs rounded-full px-2 py-1">新消息</span>
                        <button onclick="showMessages()" class="text-love-pink font-semibold">查看全部</button>
                    </div>
                </div>
                <div id="recentMessages" class="space-y-2 max-h-32 overflow-y-auto">
                    <div class="text-gray-500 dark:text-gray-400 text-center py-2">
                        还没有消息，快发送第一条爱的信息吧！
                    </div>
                </div>
                <button onclick="sendMessage()" 
                        class="w-full mt-3 gradient-bg text-white rounded-lg py-2 font-semibold">
                    ✉️ 发送爱的信息
                </button>
            </div>

            <!-- 功能按钮 -->
            <div class="m-4 grid grid-cols-2 gap-4">
                <button onclick="showGiftSuggestions()" 
                        class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 text-center">
                    <div class="text-2xl mb-2">🎁</div>
                    <div class="font-semibold text-gray-800 dark:text-white">礼物推荐</div>
                </button>
                
                <button onclick="showDateIdeas()" 
                        class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 text-center">
                    <div class="text-2xl mb-2">💑</div>
                    <div class="font-semibold text-gray-800 dark:text-white">约会计划</div>
                </button>
                
                <button onclick="showChatHelper()" 
                        class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 text-center">
                    <div class="text-2xl mb-2">💬</div>
                    <div class="font-semibold text-gray-800 dark:text-white">聊天助手</div>
                </button>
                
                <button onclick="showLoveNotes()" 
                        class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 text-center">
                    <div class="text-2xl mb-2">💌</div>
                    <div class="font-semibold text-gray-800 dark:text-white">情话大全</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 弹出框模板 -->
    <div id="modalOverlay" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="min-h-screen flex items-center justify-center p-4">
            <div class="bg-white dark:bg-gray-800 rounded-lg max-w-md w-full max-h-[80vh] overflow-y-auto">
                <div class="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
                    <h3 id="modalTitle" class="text-lg font-bold text-gray-800 dark:text-white"></h3>
                    <button onclick="closeModal()" class="text-gray-500 hover:text-gray-700">✕</button>
                </div>
                <div id="modalContent" class="p-4">
                    <!-- 动态内容 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        // 应用状态
        let appState = {
            userType: '',
            userName: '',
            partnerName: '',
            anniversaryDate: '',
            partnerBirthday: '',
            apiKey: '',
            suggestions: [],
            currentSuggestionIndex: 0
        };

        // 预设建议数据库
        const suggestionDatabase = {
            boyfriend: {
                daily: [
                    "给她发个早安信息，让她知道你想到了她",
                    "询问她今天的心情和计划",
                    "准备一个小惊喜，比如她喜欢的零食",
                    "主动分享你今天的有趣经历",
                    "关心她的工作或学习进展",
                    "计划一个周末的约会活动",
                    "给她一个温暖的拥抱",
                    "告诉她一个让你想到她的小事情"
                ],
                special: [
                    "记住她的重要日子和偏好",
                    "在她疲惫时主动承担家务",
                    "认真倾听她的烦恼，给予支持",
                    "偶尔制造浪漫惊喜",
                    "尊重她的个人空间和朋友",
                    "在她面前夸奖她，让她有面子",
                    "学会道歉，承认错误不丢脸"
                ]
            },
            girlfriend: {
                daily: [
                    "给他发个鼓励的信息，支持他的工作",
                    "询问他今天是否有压力需要分担",
                    "准备他喜欢的食物或饮品",
                    "分享一些有趣的内容让他开心",
                    "关心他的身体健康状况",
                    "计划一些两人的放松时光",
                    "给他一个理解的拥抱",
                    "告诉他你为他感到骄傲的事情"
                ],
                special: [
                    "给他足够的个人空间和朋友时间",
                    "在他努力工作时给予理解和支持",
                    "用行动表达关爱，而不只是言语",
                    "偶尔撒娇，但保持独立",
                    "在公开场合给他面子和尊重",
                    "学会沟通技巧，避免冷战",
                    "保持自己的兴趣爱好和成长"
                ]
            }
        };

        const giftSuggestions = {
            boyfriend: [
                "💎 精致的饰品 - 项链、手链或耳环",
                "🌹 一束她最爱的花 + 手写卡片",
                "🍰 定制的生日蛋糕或甜品",
                "📚 她感兴趣领域的书籍",
                "🧸 可爱的玩偶或抱枕",
                "💄 高质量的护肤品或化妆品",
                "🎵 制作专属的歌单或音乐盒",
                "📷 记录你们回忆的相册"
            ],
            girlfriend: [
                "👔 高质量的衬衫或领带",
                "⌚ 实用的手表或配件",
                "🎮 他喜欢的游戏或数码产品",
                "🏃‍♂️ 运动装备或健身用品",
                "☕ 精品咖啡豆或茶叶",
                "📱 手机配件或数码周边",
                "🎧 高质量的耳机或音响",
                "💼 实用的工作包或钱包"
            ]
        };

        const dateIdeas = [
            "🌅 一起看日出或日落",
            "🍳 在家一起做饭，尝试新菜谱",
            "🎬 看一部你们都想看的电影",
            "🚶‍♀️ 公园里散步聊天",
            "🎨 一起画画或手工制作",
            "📸 在城市里拍照打卡",
            "🎵 去KTV唱歌或听音乐会",
            "🍕 尝试新的餐厅或咖啡厅",
            "🎪 逛游乐园或展览",
            "🧩 一起玩桌游或拼图"
        ];

        const loveQuotes = {
            boyfriend: [
                "你是我心中最亮的星星 ✨",
                "和你在一起的每一天都是礼物 🎁",
                "你的笑容是我最喜欢的风景 😊",
                "有你在身边，我什么都不怕 💪",
                "你就是我想要的全部 💕",
                "我想和你一起慢慢变老 👫",
                "你是我生命中最美好的意外 🌟",
                "爱你不是三分钟热度，而是深思熟虑 💭"
            ],
            girlfriend: [
                "你是我见过最棒的男孩 🌟",
                "有你保护我，我觉得很安全 🛡️",
                "你努力的样子真的很帅 😎",
                "我相信你能做成任何事情 💪",
                "你的怀抱是我最喜欢的地方 🤗",
                "和你在一起我变得更好 ✨",
                "你是我的超级英雄 🦸‍♂️",
                "未来我想和你一起创造 🌈"
            ]
        };

        // 用户选择函数
        function selectUser(type) {
            appState.userType = type;
            document.getElementById('userSelection').classList.add('hidden');
            document.getElementById('configPanel').classList.remove('hidden');
        }

        // 保存配置
        function saveConfig() {
            appState.userName = document.getElementById('userName').value;
            appState.partnerName = document.getElementById('partnerName').value;
            appState.anniversaryDate = document.getElementById('anniversaryDate').value;
            appState.partnerBirthday = document.getElementById('partnerBirthday').value;
            appState.apiKey = document.getElementById('apiKey').value;

            if (!appState.userName || !appState.partnerName) {
                alert('请填写姓名信息');
                return;
            }

            // 保存到本地存储
            localStorage.setItem('coupleAI', JSON.stringify(appState));

            // 显示主应用
            initMainApp();
        }

        // 初始化主应用
        function initMainApp() {
            document.getElementById('configPanel').classList.add('hidden');
            document.getElementById('mainApp').classList.remove('hidden');

            // 设置界面
            const userIcon = appState.userType === 'boyfriend' ? '🤵' : '👩';
            const title = appState.userType === 'boyfriend' ? '男友助手' : '女友助手';
            
            document.getElementById('userIcon').textContent = userIcon;
            document.getElementById('appTitle').textContent = title;
            document.getElementById('subtitle').textContent = `为 ${appState.partnerName} 专属定制`;

            // 生成提醒和建议
            generateDailyReminders();
            generateAISuggestions();
            updateRelationshipDays();
        }

        // 生成每日提醒
        function generateDailyReminders() {
            const reminders = [];
            const today = new Date();

            // 检查生日提醒
            if (appState.partnerBirthday) {
                const birthday = new Date(appState.partnerBirthday);
                const thisYearBirthday = new Date(today.getFullYear(), birthday.getMonth(), birthday.getDate());
                const daysToBirthday = Math.ceil((thisYearBirthday - today) / (1000 * 60 * 60 * 24));
                
                if (daysToBirthday >= 0 && daysToBirthday <= 7) {
                    reminders.push({
                        icon: '🎂',
                        text: daysToBirthday === 0 ? `今天是${appState.partnerName}的生日！` : `${appState.partnerName}的生日还有${daysToBirthday}天`
                    });
                }
            }

            // 检查纪念日提醒
            if (appState.anniversaryDate) {
                const anniversary = new Date(appState.anniversaryDate);
                const thisYearAnniversary = new Date(today.getFullYear(), anniversary.getMonth(), anniversary.getDate());
                const daysToAnniversary = Math.ceil((thisYearAnniversary - today) / (1000 * 60 * 60 * 24));
                
                if (daysToAnniversary >= 0 && daysToAnniversary <= 7) {
                    reminders.push({
                        icon: '💕',
                        text: daysToAnniversary === 0 ? `今天是你们的纪念日！` : `你们的纪念日还有${daysToAnniversary}天`
                    });
                }
            }

            // 周末提醒
            if (today.getDay() === 5) {
                reminders.push({
                    icon: '🎉',
                    text: '周末到了，计划一些特别的活动吧'
                });
            }

            // 默认提醒
            if (reminders.length === 0) {
                reminders.push({
                    icon: '💝',
                    text: '今天也要好好爱她/他哦'
                });
            }

            const reminderHTML = reminders.map(reminder => 
                `<div class="flex items-center space-x-2 text-gray-600 dark:text-gray-400">
                    <span>${reminder.icon}</span>
                    <span>${reminder.text}</span>
                </div>`
            ).join('');

            document.getElementById('dailyReminders').innerHTML = reminderHTML;
        }

        // 生成AI建议
        function generateAISuggestions() {
            const suggestions = suggestionDatabase[appState.userType];
            const allSuggestions = [...suggestions.daily, ...suggestions.special];
            
            // 随机选择建议
            const randomSuggestion = allSuggestions[Math.floor(Math.random() * allSuggestions.length)];
            
            const suggestionHTML = `
                <div class="bg-gradient-to-r from-love-pink to-love-purple text-white rounded-lg p-4">
                    <div class="flex items-start space-x-3">
                        <div class="text-2xl">💡</div>
                        <div class="flex-1">
                            <p class="text-white">${randomSuggestion}</p>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('aiSuggestions').innerHTML = suggestionHTML;
        }

        // 获取新建议
        function getNewSuggestion() {
            trackUserAction('request_new_suggestion', {
                currentSuggestionType: 'ai_advice',
                timeOfRequest: new Date().getHours()
            });
            generateAISuggestions();
        }

        // 更新恋爱天数
        function updateRelationshipDays() {
            if (appState.anniversaryDate) {
                const anniversary = new Date(appState.anniversaryDate);
                const today = new Date();
                const daysTogether = Math.floor((today - anniversary) / (1000 * 60 * 60 * 24));
                
                document.getElementById('relationshipDays').textContent = `❤️ 在一起 ${daysTogether} 天`;
            }
        }

        // 显示礼物建议
        function showGiftSuggestions() {
            trackUserAction('view_gift_suggestions', {
                userType: appState.userType,
                relationshipStage: calculateRelationshipDays() > 365 ? 'long_term' : 'new'
            });
            
            const gifts = giftSuggestions[appState.userType];
            const giftHTML = gifts.map((gift, index) => 
                `<div class="border border-gray-200 dark:border-gray-600 rounded-lg p-3 mb-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700" 
                      onclick="trackGiftClick('${gift}', ${index})">
                    ${gift}
                </div>`
            ).join('');
            
            showModal('🎁 礼物推荐', giftHTML);
        }

        function trackGiftClick(gift, index) {
            trackUserAction('select_gift_suggestion', {
                giftDescription: gift,
                giftIndex: index,
                category: gift.split(' ')[1] // 简单分类提取
            });
        }

        // 显示约会想法
        function showDateIdeas() {
            const dateHTML = dateIdeas.map(idea => 
                `<div class="border border-gray-200 dark:border-gray-600 rounded-lg p-3 mb-2">
                    ${idea}
                </div>`
            ).join('');
            
            showModal('💑 约会想法', dateHTML);
        }

        // 显示聊天助手
        function showChatHelper() {
            const chatHTML = `
                <div class="space-y-4">
                    <div class="bg-yellow-50 dark:bg-yellow-900/30 border border-yellow-200 dark:border-yellow-700 rounded-lg p-4">
                        <h4 class="font-semibold text-yellow-800 dark:text-yellow-200 mb-2">💬 聊天技巧</h4>
                        <ul class="text-sm text-yellow-700 dark:text-yellow-300 space-y-1">
                            <li>• 多问开放性问题，了解TA的想法</li>
                            <li>• 认真倾听，给予积极回应</li>
                            <li>• 分享你的日常，让TA了解你</li>
                            <li>• 适时表达关心和爱意</li>
                        </ul>
                    </div>
                    
                    <div class="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
                        <h4 class="font-semibold text-blue-800 dark:text-blue-200 mb-2">🌟 话题建议</h4>
                        <div class="text-sm text-blue-700 dark:text-blue-300 space-y-1">
                            <div>• "今天有什么开心的事吗？"</div>
                            <div>• "我们下次想去哪里玩？"</div>
                            <div>• "你最近有什么想法想分享？"</div>
                            <div>• "我今天想到你了，因为..."</div>
                        </div>
                    </div>
                </div>
            `;
            
            showModal('💬 聊天助手', chatHTML);
        }

        // 显示情话大全
        function showLoveNotes() {
            const quotes = loveQuotes[appState.userType];
            const quoteHTML = quotes.map(quote => 
                `<div class="border border-gray-200 dark:border-gray-600 rounded-lg p-3 mb-2 text-center">
                    ${quote}
                </div>`
            ).join('');
            
            showModal('💌 情话大全', quoteHTML);
        }

        // 显示设置
        function showSettings() {
            const settingsHTML = `
                <div class="space-y-4">
                    <button onclick="showAnalytics()" class="w-full text-left border border-gray-200 dark:border-gray-600 rounded-lg p-3">
                        📊 查看数据分析
                    </button>
                    <button onclick="editProfile()" class="w-full text-left border border-gray-200 dark:border-gray-600 rounded-lg p-3">
                        👤 编辑个人信息
                    </button>
                    <button onclick="exportData()" class="w-full text-left border border-gray-200 dark:border-gray-600 rounded-lg p-3">
                        📤 导出数据
                    </button>
                    <button onclick="resetApp()" class="w-full text-left border border-gray-200 dark:border-gray-600 rounded-lg p-3 text-red-600">
                        🔄 重置应用
                    </button>
                </div>
            `;
            
            showModal('⚙️ 设置', settingsHTML);
        }

        // 数据分析展示
        function showAnalytics() {
            const analytics = generateAnalytics();
            
            const analyticsHTML = `
                <div class="space-y-4">
                    <div class="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
                        <h4 class="font-semibold text-blue-800 dark:text-blue-200 mb-3">📈 使用统计</h4>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span>总使用次数:</span>
                                <span class="font-semibold">${analytics.totalActions}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>最常用功能:</span>
                                <span class="font-semibold">${analytics.mostUsedFeature}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>使用天数:</span>
                                <span class="font-semibold">${analytics.activeDays} 天</span>
                            </div>
                        </div>
                    </div>

                    <div class="bg-pink-50 dark:bg-pink-900/30 border border-pink-200 dark:border-pink-700 rounded-lg p-4">
                        <h4 class="font-semibold text-pink-800 dark:text-pink-200 mb-3">💕 偏好分析</h4>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span>最爱消息类型:</span>
                                <span class="font-semibold">${analytics.favoriteMessageType || '尚无数据'}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>活跃时间段:</span>
                                <span class="font-semibold">${analytics.activeTimeRange}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>学习程度:</span>
                                <span class="font-semibold">${analytics.learningLevel}%</span>
                            </div>
                        </div>
                    </div>

                    <div class="bg-purple-50 dark:bg-purple-900/30 border border-purple-200 dark:border-purple-700 rounded-lg p-4">
                        <h4 class="font-semibold text-purple-800 dark:text-purple-200 mb-3">🎯 个性化建议</h4>
                        <div class="text-sm space-y-2">
                            ${analytics.personalizedSuggestions.map(suggestion => 
                                `<div class="flex items-start space-x-2">
                                    <span class="text-purple-500">•</span>
                                    <span>${suggestion}</span>
                                </div>`
                            ).join('')}
                        </div>
                    </div>

                    <button onclick="optimizeRecommendations()" 
                            class="w-full gradient-bg text-white rounded-lg py-3 font-semibold">
                        🧠 优化推荐算法
                    </button>
                </div>
            `;
            
            showModal('📊 智能分析报告', analyticsHTML);
        }

        // 生成分析报告
        function generateAnalytics() {
            const behaviorData = userAnalytics.behaviorData;
            const preferences = userAnalytics.preferences;
            
            // 计算基础统计
            const totalActions = behaviorData.length;
            const uniqueDays = new Set(behaviorData.map(item => 
                new Date(item.timestamp).toDateString()
            )).size;
            
            // 找出最常用功能
            const featureCount = preferences.featureUsage || {};
            const mostUsedFeature = Object.keys(featureCount).reduce((a, b) => 
                featureCount[a] > featureCount[b] ? a : b, '礼物推荐'
            );
            
            // 分析活跃时间
            const timePrefs = preferences.timePreferences || {};
            const activeHour = Object.keys(timePrefs).reduce((a, b) => 
                timePrefs[a] > timePrefs[b] ? a : b, '20'
            );
            const activeTimeRange = getTimeRange(parseInt(activeHour));
            
            // 分析消息偏好
            const messageTypes = preferences.messageTypes || {};
            const favoriteMessageType = Object.keys(messageTypes).reduce((a, b) => 
                messageTypes[a] > messageTypes[b] ? a : b, null
            );
            
            // 计算学习程度
            const learningLevel = Math.min(100, Math.floor((totalActions / 50) * 100));
            
            // 生成个性化建议
            const personalizedSuggestions = generatePersonalizedSuggestions(preferences);
            
            return {
                totalActions,
                activeDays: uniqueDays,
                mostUsedFeature: translateFeatureName(mostUsedFeature),
                activeTimeRange,
                favoriteMessageType: translateMessageType(favoriteMessageType),
                learningLevel,
                personalizedSuggestions
            };
        }

        function getTimeRange(hour) {
            if (hour >= 6 && hour < 12) return '早晨 (6-12点)';
            if (hour >= 12 && hour < 18) return '下午 (12-18点)';
            if (hour >= 18 && hour < 24) return '晚上 (18-24点)';
            return '深夜 (0-6点)';
        }

        function translateFeatureName(feature) {
            const translations = {
                'view_gift_suggestions': '礼物推荐',
                'send_message': '发送消息',
                'request_new_suggestion': '获取建议',
                'app_start': '应用启动'
            };
            return translations[feature] || feature;
        }

        function translateMessageType(type) {
            const translations = {
                'love': '爱意表达',
                'care': '关怀问候', 
                'encourage': '鼓励支持'
            };
            return translations[type] || type;
        }

        function generatePersonalizedSuggestions(preferences) {
            const suggestions = [];
            
            // 基于使用时间的建议
            const timePrefs = preferences.timePreferences || {};
            const activeHours = Object.keys(timePrefs);
            if (activeHours.includes('20') || activeHours.includes('21')) {
                suggestions.push('你经常在晚上使用，建议设置睡前温馨提醒');
            }
            
            // 基于功能使用的建议
            const features = preferences.featureUsage || {};
            if (features.view_gift_suggestions > features.send_message) {
                suggestions.push('你很重视礼物，建议关注节日提醒功能');
            }
            
            // 基于消息类型的建议
            const messageTypes = preferences.messageTypes || {};
            if (messageTypes.love > (messageTypes.care || 0)) {
                suggestions.push('你偏爱表达爱意，建议多关注浪漫约会计划');
            }
            
            // 默认建议
            if (suggestions.length === 0) {
                suggestions.push('继续使用应用来获得更个性化的建议');
                suggestions.push('尝试不同功能来丰富你的使用体验');
            }
            
            return suggestions;
        }

        // 优化推荐算法
        function optimizeRecommendations() {
            const preferences = userAnalytics.preferences;
            
            // 基于学习到的偏好更新建议权重
            if (preferences.messageTypes) {
                const favoriteType = Object.keys(preferences.messageTypes).reduce((a, b) => 
                    preferences.messageTypes[a] > preferences.messageTypes[b] ? a : b
                );
                
                // 保存偏好到应用状态
                appState.favoriteMessageType = favoriteType;
                localStorage.setItem('coupleAI', JSON.stringify(appState));
            }
            
            alert('🧠 推荐算法已优化！将为你提供更个性化的建议。');
            closeModal();
        }

        // 数据导出功能
        function exportData() {
            const exportData = {
                userProfile: appState,
                behaviorData: userAnalytics.behaviorData,
                preferences: userAnalytics.preferences,
                messages: getMessages(),
                exportDate: new Date().toISOString()
            };
            
            const dataStr = JSON.stringify(exportData, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            
            const link = document.createElement('a');
            link.href = url;
            link.download = `情侣AI助手数据_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            alert('📤 数据导出成功！');
        }

        // 消息功能
        function sendMessage() {
            const messageHTML = `
                <div class="space-y-4">
                    <div class="text-center mb-4">
                        <div class="text-2xl mb-2">💌</div>
                        <h4 class="font-bold text-gray-800 dark:text-white">发送给 ${appState.partnerName}</h4>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            选择消息类型
                        </label>
                        <div class="grid grid-cols-2 gap-2 mb-4">
                            <button onclick="selectMessageType('love')" 
                                    class="border-2 border-love-pink text-love-pink rounded-lg p-3 hover:bg-love-pink hover:text-white transition-colors">
                                💕 爱意表达
                            </button>
                            <button onclick="selectMessageType('care')" 
                                    class="border-2 border-love-blue text-love-blue rounded-lg p-3 hover:bg-love-blue hover:text-white transition-colors">
                                🤗 关怀问候
                            </button>
                            <button onclick="selectMessageType('encourage')" 
                                    class="border-2 border-love-purple text-love-purple rounded-lg p-3 hover:bg-love-purple hover:text-white transition-colors">
                                💪 鼓励支持
                            </button>
                            <button onclick="selectMessageType('custom')" 
                                    class="border-2 border-gray-400 text-gray-600 rounded-lg p-3 hover:bg-gray-400 hover:text-white transition-colors">
                                ✍️ 自定义
                            </button>
                        </div>
                    </div>
                    
                    <div id="messageTemplates" class="hidden">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            选择模板或自定义
                        </label>
                        <div id="templateList" class="space-y-2 mb-4 max-h-40 overflow-y-auto">
                            <!-- 动态生成模板 -->
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            消息内容
                        </label>
                        <textarea id="messageContent" rows="4" placeholder="输入你想说的话..." 
                                  class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-base focus:outline-none focus:ring-2 focus:ring-love-pink bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"></textarea>
                    </div>
                    
                    <div class="flex space-x-2">
                        <button onclick="doSendMessage()" 
                                class="flex-1 gradient-bg text-white rounded-lg py-3 font-semibold">
                            💌 发送消息
                        </button>
                        <button onclick="closeModal()" 
                                class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400">
                            取消
                        </button>
                    </div>
                </div>
            `;
            
            showModal('✉️ 发送爱的信息', messageHTML);
        }

        function selectMessageType(type) {
            const templates = {
                love: [
                    "想你了 💕",
                    "爱你，今天也要开心哦 😊",
                    "你是我心中最亮的星星 ✨",
                    "和你在一起的每一天都很幸福 🥰",
                    "你的笑容是我最喜欢的风景 😊"
                ],
                care: [
                    "今天过得怎么样？💝",
                    "记得按时吃饭哦 🍽️",
                    "天气变化记得添衣服 👗",
                    "工作累了就休息一下 😴",
                    "有什么烦恼可以和我分享 🤗"
                ],
                encourage: [
                    "你一定可以的！💪",
                    "我相信你能做得很好 🌟",
                    "加油，我永远支持你 💕",
                    "你已经很棒了 👏",
                    "不管发生什么，我都在你身边 🤝"
                ],
                custom: []
            };

            const templateList = document.getElementById('templateList');
            const messageTemplates = document.getElementById('messageTemplates');
            
            if (type === 'custom') {
                messageTemplates.classList.add('hidden');
                document.getElementById('messageContent').focus();
                return;
            }

            const templateHTML = templates[type].map(template => 
                `<button onclick="selectTemplate('${template}')" 
                         class="w-full text-left border border-gray-200 dark:border-gray-600 rounded-lg p-2 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                    ${template}
                </button>`
            ).join('');

            templateList.innerHTML = templateHTML;
            messageTemplates.classList.remove('hidden');
        }

        function selectTemplate(template) {
            document.getElementById('messageContent').value = template;
        }

        function doSendMessage() {
            const content = document.getElementById('messageContent').value.trim();
            if (!content) {
                alert('请输入消息内容');
                return;
            }

            const message = {
                id: Date.now(),
                from: appState.userName,
                to: appState.partnerName,
                content: content,
                timestamp: new Date().toISOString(),
                read: false,
                type: appState.userType
            };

            // 保存消息到本地存储
            saveMessage(message);
            
            // 显示成功提示
            alert('💌 消息发送成功！');
            closeModal();
            
            // 刷新消息显示
            updateRecentMessages();
        }

        function saveMessage(message) {
            let messages = JSON.parse(localStorage.getItem('coupleMessages') || '[]');
            messages.push(message);
            
            // 只保留最近100条消息
            if (messages.length > 100) {
                messages = messages.slice(-100);
            }
            
            localStorage.setItem('coupleMessages', JSON.stringify(messages));
        }

        function getMessages() {
            return JSON.parse(localStorage.getItem('coupleMessages') || '[]');
        }

        function updateRecentMessages() {
            const messages = getMessages();
            const myMessages = messages.filter(msg => msg.from === appState.userName);
            const partnerMessages = messages.filter(msg => msg.to === appState.userName);
            
            const recentMessagesDiv = document.getElementById('recentMessages');
            
            if (messages.length === 0) {
                recentMessagesDiv.innerHTML = `
                    <div class="text-gray-500 dark:text-gray-400 text-center py-2">
                        还没有消息，快发送第一条爱的信息吧！
                    </div>
                `;
                return;
            }

            // 显示最近的消息
            const allMessages = [...myMessages, ...partnerMessages]
                .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
                .slice(0, 3);

            const messagesHTML = allMessages.map(msg => {
                const time = new Date(msg.timestamp).toLocaleString('zh-CN', {
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
                
                const isMine = msg.from === appState.userName;
                const icon = isMine ? '📤' : '📥';
                const name = isMine ? '我' : msg.from;
                
                return `
                    <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-2">
                        <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
                            <span>${icon} ${name}</span>
                            <span>${time}</span>
                        </div>
                        <div class="text-sm text-gray-700 dark:text-gray-300">${msg.content}</div>
                    </div>
                `;
            }).join('');

            recentMessagesDiv.innerHTML = messagesHTML;

            // 显示新消息提醒
            const unreadCount = partnerMessages.filter(msg => !msg.read).length;
            const notification = document.getElementById('messageNotification');
            if (unreadCount > 0) {
                notification.textContent = `${unreadCount}条新消息`;
                notification.classList.remove('hidden');
            } else {
                notification.classList.add('hidden');
            }
        }

        function showMessages() {
            const messages = getMessages();
            const myMessages = messages.filter(msg => msg.from === appState.userName);
            const partnerMessages = messages.filter(msg => msg.to === appState.userName);
            
            // 标记所有消息为已读
            partnerMessages.forEach(msg => msg.read = true);
            localStorage.setItem('coupleMessages', JSON.stringify(messages));
            
            const allMessages = [...myMessages, ...partnerMessages]
                .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

            let messagesHTML = '';
            
            if (allMessages.length === 0) {
                messagesHTML = `
                    <div class="text-center text-gray-500 dark:text-gray-400 py-8">
                        <div class="text-4xl mb-4">💌</div>
                        <p>还没有消息记录</p>
                        <p class="text-sm mt-2">发送第一条爱的信息吧！</p>
                    </div>
                `;
            } else {
                messagesHTML = `
                    <div class="space-y-3 max-h-96 overflow-y-auto">
                        ${allMessages.map(msg => {
                            const time = new Date(msg.timestamp).toLocaleString('zh-CN');
                            const isMine = msg.from === appState.userName;
                            
                            return `
                                <div class="border-l-4 ${isMine ? 'border-love-pink bg-pink-50 dark:bg-pink-900/20' : 'border-love-blue bg-blue-50 dark:bg-blue-900/20'} pl-4 py-2">
                                    <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
                                        <span>${isMine ? '我' : msg.from} → ${isMine ? msg.to : '我'}</span>
                                        <span>${time}</span>
                                    </div>
                                    <div class="text-gray-700 dark:text-gray-300">${msg.content}</div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                    
                    <div class="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                        <button onclick="closeModal(); sendMessage();" 
                                class="w-full gradient-bg text-white rounded-lg py-2 font-semibold">
                            💌 发送新消息
                        </button>
                    </div>
                `;
            }
            
            showModal('💕 消息记录', messagesHTML);
            updateRecentMessages(); // 更新主界面显示
        }

        // 重置应用
        function resetApp() {
            if (confirm('确定要重置应用吗？所有数据将被清除。')) {
                localStorage.removeItem('coupleAI');
                localStorage.removeItem('coupleMessages');
                location.reload();
            }
        }

        // 显示模态框
        function showModal(title, content) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalContent').innerHTML = content;
            document.getElementById('modalOverlay').classList.remove('hidden');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.add('hidden');
        }

        // 数据收集和分析功能
        const userAnalytics = {
            behaviorData: JSON.parse(localStorage.getItem('userBehavior') || '[]'),
            preferences: JSON.parse(localStorage.getItem('userPreferences') || '{}'),
            interactions: JSON.parse(localStorage.getItem('userInteractions') || '[]')
        };

        // 行为追踪函数
        function trackUserAction(actionType, actionData) {
            const behaviorEntry = {
                id: Date.now(),
                actionType: actionType,
                actionData: actionData,
                timestamp: new Date().toISOString(),
                context: {
                    userType: appState.userType,
                    timeOfDay: new Date().getHours(),
                    dayOfWeek: new Date().getDay(),
                    relationshipDays: calculateRelationshipDays()
                }
            };
            
            userAnalytics.behaviorData.push(behaviorEntry);
            
            // 只保留最近1000条记录
            if (userAnalytics.behaviorData.length > 1000) {
                userAnalytics.behaviorData = userAnalytics.behaviorData.slice(-1000);
            }
            
            localStorage.setItem('userBehavior', JSON.stringify(userAnalytics.behaviorData));
            
            // 实时学习用户偏好
            updateUserPreferences(actionType, actionData);
        }

        // 用户偏好学习
        function updateUserPreferences(actionType, actionData) {
            const preferences = userAnalytics.preferences;
            
            // 记录功能使用偏好
            if (!preferences.featureUsage) preferences.featureUsage = {};
            preferences.featureUsage[actionType] = (preferences.featureUsage[actionType] || 0) + 1;
            
            // 记录时间偏好
            if (!preferences.timePreferences) preferences.timePreferences = {};
            const hour = new Date().getHours();
            preferences.timePreferences[hour] = (preferences.timePreferences[hour] || 0) + 1;
            
            // 记录消息类型偏好
            if (actionType === 'send_message' && actionData.messageType) {
                if (!preferences.messageTypes) preferences.messageTypes = {};
                preferences.messageTypes[actionData.messageType] = (preferences.messageTypes[actionData.messageType] || 0) + 1;
            }
            
            // 记录礼物类型偏好
            if (actionType === 'view_gift_suggestion' && actionData.category) {
                if (!preferences.giftCategories) preferences.giftCategories = {};
                preferences.giftCategories[actionData.category] = (preferences.giftCategories[actionData.category] || 0) + 1;
            }
            
            localStorage.setItem('userPreferences', JSON.stringify(preferences));
        }

        // 计算恋爱天数
        function calculateRelationshipDays() {
            if (!appState.anniversaryDate) return 0;
            const anniversary = new Date(appState.anniversaryDate);
            const today = new Date();
            return Math.floor((today - anniversary) / (1000 * 60 * 60 * 24));
        }

        // 页面加载时检查保存的数据
        window.addEventListener('load', function() {
            const savedData = localStorage.getItem('coupleAI');
            if (savedData) {
                appState = JSON.parse(savedData);
                initMainApp();
                
                // 追踪应用启动
                trackUserAction('app_start', {
                    sessionId: Date.now(),
                    userType: appState.userType
                });
            }
        });

        // 暗黑模式检测
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.documentElement.classList.add('dark');
        }
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
            if (event.matches) {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
        });
    </script>
</body>
</html>